<template>
  <div class="purchase-incoming-warp disabled-warp" :style="`${!formData ? 'height: calc(100vh - 104px);' : 'height: 100%;' } padding: 20px;` ">
    <div class="dashboard-container" v-if="!formData"
         style=" padding: 20px 12px 10px;  ">
      <div
          style="line-height: 16px; flex-wrap: wrap;   align-items: center;  font-size: 16px; font-family: Source Han Sans CN;font-weight: bold;color: #2F3745; ">
        <div class="dashboard-inner">
          库存盘点
          <el-tooltip class="item" effect="dark" content="温馨提示：对应列可以通过拖动改变表格宽度" placement="top">
            <i style="position: relative; left: 6px; top: 2px;" class="header-icon el-icon-info"></i>
          </el-tooltip>
        </div>
      </div>
    </div>

    <div :style="`${!formData ? 'height: calc(100% - 100px);' : 'height: calc(100% - 110px);'} display: flex;`">
      <div class="right-content" style="background: #fff; width: 100%;">
        <div
            :style="`margin-left: 12px; position: relative; height: 100%; width: calc(100% - 24px);`">
          <common-operation-form :list="list"/>
          <el-table style="margin-top: 15px; " fit :height="!formData ? windowHeight - 45 : windowHeight - 15" show-summary
                    @select="changeevent" ref="tableRef" :summary-method="getSummaries"
                    v-loading="table.loading" :data="table.data" border >
            <el-table-column :prop="item.prop"  v-for="(item, index) in table.header1"
                             :width="item.width || 'auto'" :align="`center`"
                             :label="item.label">
              <template slot="header" slot-scope="{column}">
                <div style="display: flex; justify-content: center;">
                  <span v-if="item.required" class="text-center text-star">*</span>
                  {{ item.label }}
                </div>
              </template>
              <template slot-scope="scope">
                <el-popover v-model="scope.row.popoverShow" :popper-class="'right-content-popper-table'"
                            placement="bottom-start" width="720" v-if="item.prop === 'productName'"
                            trigger="click" @show="item.popoverShowEvent(item, scope.row.productName)">
                  <el-table v-loading="item.tableLoading" @row-click="(v) => item.tableEvent(v, scope, item)"
                            highlight-current-row :data="item.tableData">
                    <el-table-column width="100" align="center" property="productName" label="商品条码"></el-table-column>
                    <el-table-column width="100" align="center" property="name" label="商品名称"></el-table-column>
                    <el-table-column width="100" align="center" property="specification" label="规格"></el-table-column>
                    <el-table-column width="70" align="center" property="address" label="属性"></el-table-column>
                    <el-table-column width="70" align="center" property="price" label="进货价">
                      <template slot-scope="scope">
                        <span v-if="isNotANumberOrEmpty(scope.row['price'])">0</span>
                        <span v-else>{{scope.row['price']}}</span>
                      </template>
                    </el-table-column>
                    <el-table-column width="70" align="center" property="unit" label="单位"></el-table-column>
                    <el-table-column width="70" align="center" property="inventory" label="总库存"></el-table-column>
                    <el-table-column width="100" align="center" property="shelfLocation" label="所在货位"></el-table-column>
                  </el-table>
                  <el-input v-model="scope.row[item.prop]" @click.native.stop="(v) => item.clickEvent(v, item, scope)"
                            @input="(v) => item.inputEvent(v, item)" slot="reference"
                            placeholder="搜索名称、编号、条形码"></el-input>
                </el-popover>

                <span  v-else-if="item.prop === 'price'">
                    <span v-if="isNotANumberOrEmpty(scope.row['price'])">0</span>
                    <span v-else>{{scope.row['price']}}</span>
                </span>
                <el-input v-else-if="item.prop === 'inventory'"   :precision="2"
                          @blur="calculateValue(scope.row, scope, 'inventory')"
                          type="number" v-model.number="scope.row[item.prop]"></el-input>
                <span v-else-if="item.prop === 'profitAndLossInventory'">
                  {{ calculateTwoValue(scope.row['inventory'], scope.row['bookInventory'], 'minus', 2) }}
                </span>
                <span v-else-if="item.prop === 'profitAndLossMoney'">
                  {{ calculateTwoValue(scope.row['inventory'], scope.row['price'], 'mul', 2) }}
                </span>
                <el-input v-else-if="item.prop === 'remarks'" v-model="scope.row[item.prop]"></el-input>
                <warehouse-select :use-disabled="true" :use-disabled-table="table.data" ref="warehouseRef" @setValue="(v) => setWarehouseValue(v, scope, item)" :value="scope.row[item.prop]" v-else-if="item.prop === 'warehouse'"/>
                <unit-select @setValue="(v) => scope.row[item.prop] = v" :value="scope.row[item.prop]" v-else-if="item.prop === 'unit'"/>
                <span style="" v-else-if="item.prop === 'type' ">
                  <span v-if="isNotANumberOrEmpty(scope.row['bookInventory'])">

                  </span>
                  <span v-else-if="scope.row['bookInventory'] === scope.row['inventory']">
                    无盈亏
                  </span>
                  <el-tag v-else-if="scope.row['bookInventory'] > scope.row['inventory']"
                          type="warning"
                          effect="dark">
                    盘亏
                  </el-tag>
                   <el-tag v-else
                           type="success"
                           effect="dark">
                    盘盈
                  </el-tag>
                </span>
                <span style="" v-else>{{ scope.row[item.prop] }}</span>
              </template>
            </el-table-column>

            <el-table-column
                label="操作" width="70">
              <template slot-scope="scope">
                <div style="display: flex;">
                  <el-tooltip content="删除" slot="reference" placement="top">
                    <el-button size="mini" @click="del(scope.$index, scope.row)" type="danger" icon="el-icon-delete"
                               circle></el-button>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <div class="right-content" :style="` width: 100%; margin-bottom: 10px; ${!formData ? '' : 'margin-top: 0;'} position: relative; background: #fff;` ">
      <div style="margin: 10px; display: flex; width: 100%;">
        <div style=" ">
          <common-operation-form :margin-top="0" :marginRight="'30px'" style="margin-top: 0;" :list="list3"/>
        </div>
        <common-operation-form :marginRight="'0px'" :margin-top="'0px'" style="text-align: right; position: absolute; right: 10px;"
                               :list="!formData ? list4 :  []" />
      </div>
    </div>
  </div>
</template>

<script>
import CommonOperationForm from "@/components/CommonOperationForm/index.vue";
import CommonDialogForm from "@/components/CommonDialogForm/index.vue";
import UnitSelect from "@/components/Unit/UnitSelect.vue";
import WarehouseSelect from "@/components/Warehouse/WarehouseSelect.vue";
import {calculateTwoValue, isValidAmount} from "@/utils";
import {getAllProduct} from "@/api/product";
import {getToken, getUserInfo, setUserInfo} from "@/utils/auth";
import {getInfo, invoice} from "@/api/user";
import {audit, getPurchaseIncomingByID} from "@/api/purchaseIncoming";
import {isNotANumberOrEmpty} from "@/utils";
import {generateInventoryAlertOrderNumber, addInventoryCheck} from "@/api/inventory";
import {deleteEmployeeByEmployeeID} from "@/api/employee";

export default {
  props: ["formData"],
  components: {CommonOperationForm, CommonDialogForm, UnitSelect, WarehouseSelect},
  data() {
    return {
      list: [
        {
          type: 'datetime',
          text: '单据日期：',
          pickerWidth: '190px',
          value: new Date(),
        },
        {
          type: 'input',
          clearable: false,
          text: '单据编号：',
          value: '',
        },
        {
          type: 'button',
          buttonIcon: 'el-icon-plus',
          buttonText: '插入行',
          buttonType: 'success',
          event: () => {
            this.addRowToTable();
            this.$nextTick(() => {
              this.$refs.tableRef.doLayout();
            });
          }
        },
      ],
      list5: [
        {
          type: 'button',
          buttonIcon: 'el-icon-plus',
          buttonText: '插入行',
          buttonType: 'success',
          event: () => {
            this.addRowToTable();
            this.$nextTick(() => {
              this.$refs.tableRef.doLayout();
            });
          }
        },
        {
          type: 'dropdown',
          contentname: '更多设置',
          trigger: 'hover',
          dropdownHideOnClick: false,
          size: 'small',
          list: [
            {
              icon: '',
              label: '需要发票',
            }
          ],
          command: (v) => {
            console.log(v, this.list[5]);
            invoice({
              userID: getUserInfo()._id,
            }).then(res => {
              this.list[5].list[0].icon = res.data.invoice ? 'el-icon-check' : '';
              let msg = res.data.invoice ? '发票功能已开启' : '发票功能已关闭';
              console.log(res.data.invoice, msg);
              getInfo(getToken()).then(res => {
                setUserInfo(res.data.data);
              });
              this.$message.success("设置成功：" +  msg);
            });
          },
        }
      ],
      list3: [
        {
          text: '制单员：',
          selectWidth: '160px',
          width: '80px',
          required: true,
          field: 'employeeSetting',
          type: 'employeeSetting',
          value: '',
        },
        {
          type: 'input',
          text: '备注：',
          value: '',
          inputWidth: '320px',
          width: '65px',
        },
      ],
      list4: [
        {
          type: 'button',
          buttonIcon: 'el-icon-s-promotion',
          buttonText: '保存',
          buttonFontSize: '18px',
          buttonHeight: '40px',
          borderLeft: '1px solid #dfe6ec',
          buttonWidth: '120px',
          paddingLeft: '12px',
          event: () => this.saveEvent(),
        },
      ],
      expansionStatus: true,
      editDialog: false,
      table: {
        data: [],
        loading: false,
        header1: [
          {
            prop: "productName",
            width: "160",
            label: "商品信息",
            required: true,
            tableData: [],
            tableLoading: false,
            popoverShow: false,
            inputEvent: (v, e) => this.inputEvent(v, e),
            clickEvent: (v, e, scope) => this.clickEvent(v, e, scope),
            tableEvent: (v, scope, e) => this.tableEvent(v, scope, e),
            popoverShowEvent: (item, productName) => {
              this.getAllProduct(item, productName);

            },
          },
          {
            "prop": "model",
            "label": "规格型号"
          },
          {
            "prop": "unit",
            "label": "单位",
            "width": "100",
          },
          {
            "prop": "warehouse",
            "label": "所属仓库",
            required: true,
            "width": "120",
          },
          {
            "prop": "bookInventory",
            "label": "账面数量"
          },
          {
            "prop": "inventory",
            required: true,
            width: '100',
            "label": "实际数量"
          },
          {
            "prop": "type",
            "label": "类型"
          },
          {
            "prop": "price",
            required: true,
            width: '100px',
            "label": "进货价"
          },
          {
            "prop": "profitAndLossInventory",
            "label": "盈亏数量"
          },
          {
            "prop": "profitAndLossMoney",
            "label": "盈亏金额"
          },
          {
            "prop": "remarks",
            "label": "备注"
          },
        ],
      },
    }
  },
  watch: {
    'table.data': {
      handler() {
        // this.$refs.warehouseRef[i].getWarehouseList(tableData._id);

        // this.useDisabledTableMethod();
        // let total = 0.0;
        // for (let i = 0; i < this.table.data.length; i++) {
        //   let data = this.table.data[i];
        //   total += parseFloat(data.totalAmount);
        // }
        // total = this.keepTwoDecimalFull(total);
        // this.list3[0].value = total;
        // this.list3[0].value2 = 0;
        // this.list2[0].value = total;
      },
      deep: true,
    },
    'formData': {
      handler() {
        console.log("441 watch")
      },
      deep: true,
    }
  },
  activated() {
    this.readData();
  },
  mounted() {
    this.readData();
    if (!this.formData) {
      this.generateInventoryAlertOrderNumber();
    }
  },
  methods: {
    calculateTwoValue,
    isNotANumberOrEmpty,
    readData() {
      if (this.formData) {
        console.log("381", this.formData);
        this.table.data = this.formData.productInfo;
        this.$nextTick(() => {
          for (let i = 0; i < this.table.data.length; i++) {
            let tableData = this.table.data[i];
            this.$refs.warehouseRef[i].getWarehouseList(tableData._id);
          }

          this.list3[0].value = this.formData.employee;
          this.list[0].value = this.formData.createDate;
          this.list[1].value = this.formData.documentNumber;
          this.list3[1].value = this.formData.remarks;

          this.$refs.tableRef.doLayout();
        });
      }
    },
    requestApi() {
      getPurchaseIncomingByID({
        _id: this.formData._id
      }).then(res => {
        console.log(res);
        let formData = res.data.data[0];
        this.$emit('setPurchaseIncomingData', formData);
      });
    },
    setWarehouseValue(v, scope, item) {
      console.log("setWarehouseValue: ", v, scope, item);
      scope.row[item.prop] = v
      if (!this.formData) { // 查看状态不能被赋值
        scope.row['bookInventory'] = v.inventory;
        scope.row['inventory'] = v.inventory;
      }

      // 库存盘点，如果某一个商品的仓库被使用，就禁用
      if (this.$refs.warehouseRef) {
        for(let i = 0; i < this.$refs.warehouseRef.length; i++) {
          let item = this.$refs.warehouseRef[i];
          item.useDisabledTableMethod();
        }
      }
    },
    setAuditStatus(auditStatus) {
      let IDList = [this.formData._id];

      audit({
        auditStatus,
        IDList,
      }).then(res => {
        this.$message.success("操作成功");
        console.log(res);
        this.requestApi();
      });
    },
    generateInventoryAlertOrderNumber() {
      generateInventoryAlertOrderNumber({
        userID: getUserInfo().userID,
      }).then(res => {
        console.log(res, 290);
        this.list[1].value = res.data.data;
      });
    },
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];

      columns.forEach((column, index) => {
        sums[index] = '';
      });
      let inventorySum = 0;
      let totalAmountSum = 0.0;
      for (let i = 0; i < data.length; i++) {
        let {inventory, totalAmount} = data[i];

        inventory = parseInt(inventory);
        totalAmount = parseFloat(totalAmount);
        if (!isNaN(inventory)) {
          inventorySum += inventory;
        }
        if (!isNaN(totalAmount)) {
          totalAmountSum += totalAmount;
        }
      }

      sums[4] = "总数量：" + inventorySum;
      sums[6] = "总金额：" + totalAmountSum;
      return sums;
    },
    getAllProduct(item, productName) {
      if (item.tableLoading)
        return;
      item.tableLoading = true;

      getAllProduct({
        userID: getUserInfo().userID,
        productName: productName,
      }).then(res => {
        item.tableData = res.data.data;
        this.$nextTick(() => {
          item.tableLoading = false;
        });
      })
    },
    tableEvent(v, scope, e) {
      console.log(v, scope, 540)
      scope.row['popoverShow'] = false;
      scope.row["productName"] = v?.productName;
      scope.row["productID"] = v?._id;
      scope.row["unit"] = v?.unit;
      scope.row["inventory"] = 0;
      scope.row["price"] = v?.price || 0;
      scope.row['_id'] = v?._id;
      scope.row['bookInventory'] = 0;
      // scope.row['inventoryID'] = v?._id;
      this.calculateValue(scope.row, scope, 'inventory');
      console.log("getWarehouseList: ", this.$refs.warehouseRef);
      // 选择完商品后 warehouseRef 得到库存和仓库信息
      this.$refs.warehouseRef[scope.$index].getWarehouseList(v?._id);
    },
    clickEvent(v, e, scope) {
      setTimeout(() => {
        scope.row['popoverShow'] = true;
      }, 100)
    },
    inputEvent(v, e) {
      console.log(v, e);
      this.getAllProduct(e, v);
      // e.tableLoading = true;
    },
    keepTwoDecimalFull(num, decimal = 2) {
      num = num.toString()
      let index = num.indexOf('.')
      if (index !== -1) {
        num = num.substring(0, decimal + index + 1)
      } else {
        num = num.substring(0)
      }
      return parseFloat(num).toFixed(decimal)
    },
    calculateValue(item, scope, inputField) {
      let index = scope.$index;
      let inventory = parseFloat(item.inventory);
      let price = parseFloat(item.price);
      let totalPrice = parseFloat(item.totalAmount);

      if (inputField === 'inventory') {
        if (isNotANumberOrEmpty(inventory) && (!isNotANumberOrEmpty(price) || !isNotANumberOrEmpty(totalPrice))) {
          inventory = 0;
        }

        if (!isNotANumberOrEmpty(price)) { // 如果 期初成本价 不为空 则优先计算 总价，不然就计算期初成本价
          totalPrice = price * inventory;
        } else {
          price = totalPrice / inventory;
        }
      }
      if (inputField === 'price') {
        if (isNotANumberOrEmpty(price) && (!isNotANumberOrEmpty(inventory) || !isNotANumberOrEmpty(totalPrice))) {
          price = 0.00;
        }

        if (!isNotANumberOrEmpty(inventory)) { // 只能计算总价
          totalPrice = price * inventory;
        }
      }
      if (inputField === 'totalAmount') {
        if (isNotANumberOrEmpty(totalPrice) && (!isNotANumberOrEmpty(inventory) || !isNotANumberOrEmpty(price))) {
          totalPrice = 0.00;
        }

        if (!isNotANumberOrEmpty(inventory)) {
          price = totalPrice / inventory;
        }
      }

      item.totalAmount = this.keepTwoDecimalFull(totalPrice);
      item.price = this.keepTwoDecimalFull(price);
      item.inventory = inventory;

      this.$set(this.table.data, index, item);
    },
    addRowToTable() {
      let arg = {};
      for (let i = 0; i < this.table.header1.length; i++) {
        let h = this.table.header1[i];
        arg[h.prop] = '';
      }
      arg['createDate'] = new Date();
      console.log(arg)
      this.table.data.push(arg);
    },
    statusChange(v) {
      this.expansionStatus = v;
    },
    edit(item) {
      let setData = () => {
        for (const inputSet of this.dialog.form) {
          for (const inputItem of inputSet) {
            inputItem['value'] = item[inputItem['field']];
          }
        }
      }

      setData();
      this.editDialog = true;
    },
    del(index, item) {
      console.log(item);
      this.table.data.splice(index, 1);
    },
    changeevent(selection, row) {
      console.log(selection, row);

    },
    submit() {
      let data = this.$refs.commondialogformref.requiredEmpty();
      if (data) {
        this.$message.error(data.requiredMessage);
        return;
      }

      data = this.$refs.commondialogformref.getData();
      data['isDisabled'] = false;
      this.dialog.form = JSON.parse(JSON.stringify(this.dialog.copyForm));
      this.table.data.push(data);
      this.editDialog = false;
      this.$message.success("添加成功");
    },
    saveEvent(audit = false) {
      if (this.table.data.length <= 0) {
        this.$message.error("请填写表格数据信息");
        return;
      }

      let {header1, data} = this.table;

      // 必填项 检查
      for (let i = 0; i < header1.length; i++) {
        for (let j = 0; j < data.length; j++) {
          if (header1[i].required && data[j][header1[i].prop] === '') {
            console.log(data[j], header1[i].prop);
            this.$message.error(`第${j + 1}行${header1[i].label}填写有误，请检查`);
            return;
          }
        }
      }

      if (this.list3[0].value === '') {
        this.$message.error("制单员不能为空");
        return;
      }




      if (this.list[1].value === '') {
        this.$message.error("请填写单据编号");
        return;
      }


      let productInfo = this.table.data;
      let employee = this.list3[0].value;
      let createDate = this.list[0].value;
      let documentNumber = this.list[1].value;
      let remarks = this.list3[1].value;
      addInventoryCheck({
        _id: this.formData && this.formData._id ? this.formData._id : '',
        productInfo, employee, display: true, audit,
        remarks, invoice,
        userID: getUserInfo().userID, documentNumber, createDate,
      }).then(res => {
        console.log(res);
        if (res.data.code === -1) {
          this.$message.error(res.data.errMsg);
          return;
        }
        this.$message.success("提交成功");

        if (this.formData) {
          this.requestApi();
        }
      });
    }
  }
}
</script>

<style lang="scss" scope>
.dashboard {
  &-container {
    background: #fff;
    box-shadow: 0px 0px 10px 0px rgba(45, 51, 65, 0.08);
    border-radius: 10px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.dashboard-inner {
  font-size: 16px;
  font-weight: 700;
  padding: 0 0 10px 0;
  color: #2f3745;
}


.el-scrollbar__view {
  height: 100%;
}

.el-scrollbar__wrap {
  overflow: scroll;
}

.box-card .el-card__body {
  height: 100%;
}

.left-content {
  line-height: 16px;
  flex-wrap: wrap;
  border-radius: 10px;
  display: flex;
  padding-top: 10px;
  align-items: center;
  font-size: 16px;
  font-family: Source Han Sans CN;
  font-weight: bold;
}


.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }

    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}


.purchase-incoming-warp .right-content {
  line-height: 16px;
  flex-wrap: wrap;
  width: 100%;
  border-radius: 10px;
  display: flex;
  padding-top: 4px;
  margin-top: 10px;
  margin-left: 0 !important;
  align-items: center;
  font-size: 16px;
  font-family: Source Han Sans CN;
  font-weight: 500;
}

.right-content-popper-table .el-table tbody tr:hover > td {
  background-color: #cfe3ec !important;
  cursor: pointer;
}

.right-content-popper-table .el-table {
  .el-table__body-wrapper {
    z-index: 2;
  }
}

.text-center {
  display: flex;
  align-content: center;
  align-items: center;
}

.text-star {
  color: red;
  font-size: 11px;
}
</style>
